package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

func main() {
	var (
		client *mongo.Client
		err    error
	)

	// 建立mongodb连接
	// mongodb://reet1:chatMMtahc@43.255.53.66:27072?authSource=admin
	// mongodb://ichunt:huntmon6699@192.168.1.237:27017/ichunt?authMechanism=SCRAM-SHA-1
	clientOptions := options.Client().ApplyURI("mongodb://reet1:chatMMtahc@43.255.53.66:27072")
	if client, err = mongo.Connect(context.TODO(), clientOptions); err != nil {
		fmt.Println("连接mongodb失败：", err)
		return
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println(" MongoDB ping err: ", err)
	}
	fmt.Println("Connected to MongoDB!")

	defer func() {
		err = client.Disconnect(context.TODO())
		if err != nil {
			fmt.Println("断开连接失败：", err)
		}
	}()
	/********* 增删改查操作 ********/

	//InsertOneDemo(client)
	//time.Sleep(time.Second*2)
	//InsertManyDemo(client)

	// DeleteOneDemo(client)
	// DeleteManyDemo(client)

	//UpdateOneDemo(client)
	//UpdateManyDemo(client)

	// SearchOneDemo(client)
	// SearchOneDataDemo(client)
	SearchMatchDemo(client)

}

type UnreadChatGroupAssistantMessage1 struct {
	RecvUid     uint32 `bson:"RecvUid"`
	AssistantID uint32 `bson:"AssistantID"`
	//最后读取游标id
	LastReadMsgID string `bson:"LastReadMsgID"`
}

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName    string    `bson:"jobName"`    // 任务名
	Command    string    `bson:"command"`    // shell命令
	Err        string    `bson:"err"`        // 脚本错误
	Content    string    `bson:"content"`    // 脚本输出
	TimePoint  TimePoint `bson:"timePoint"`  // 执行时间点
	CreateTime int64     `bson:"CreateTime"` // 创建时间
}

// 新增一条数据
func InsertOneDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	record := &LogRecord{
		JobName:    "job01",
		Command:    "echo hello",
		Err:        "err",
		Content:    "hello",
		TimePoint:  TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10},
		CreateTime: time.Now().Unix(),
	}
	var (
		result *mongo.InsertOneResult
		err    error
	)
	if result, err = collection.InsertOne(context.TODO(), record); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result)
	//// _id: 默认生成一个全局唯一ID, ObjectID：12字节的二进制
	docId := result.InsertedID.(primitive.ObjectID)
	fmt.Println("自增ID:", docId.Hex())
}

// 新增多条数据
func InsertManyDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	// records := make([]*LogRecord,0 )
	records := []interface{}{
		LogRecord{
			JobName:    "job02",
			Command:    "echo hello 2",
			Err:        "",
			Content:    "hello",
			CreateTime: time.Now().Unix(),
			TimePoint:  TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10},
		}, LogRecord{
			JobName:    "job03",
			Command:    "echo hello 3",
			Err:        "",
			Content:    "hello",
			CreateTime: time.Now().Unix(),
			TimePoint:  TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10},
		}, LogRecord{
			JobName:    "job04",
			Command:    "echo hello 4",
			Err:        "",
			Content:    "hello",
			CreateTime: time.Now().Unix(),
			TimePoint:  TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10},
		},
	}

	var (
		results *mongo.InsertManyResult
		err     error
	)
	if results, err = collection.InsertMany(context.TODO(), records); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(results)
	//// _id: 默认生成一个全局唯一ID, ObjectID：12字节的二进制
	for i := range results.InsertedIDs {
		docId := results.InsertedIDs[i].(primitive.ObjectID)
		fmt.Println("自增ID:", docId.Hex())
	}

}

// 删除一条
func DeleteOneDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	var (
		result *mongo.DeleteResult
		err    error
	)
	if result, err = collection.DeleteOne(context.TODO(), bson.M{"jobName": "job02"}); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result)
	fmt.Println("删除的数量为:", result.DeletedCount)

}

// 删除多条
func DeleteManyDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	var (
		result *mongo.DeleteResult
		err    error
	)
	if result, err = collection.DeleteMany(context.TODO(), bson.M{"content": "hello"}); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result)
	fmt.Println("删除的数量为:", result.DeletedCount)
}

// 修改一条
func UpdateOneDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	var (
		result *mongo.UpdateResult
		err    error
	)

	if result, err = collection.UpdateOne(context.TODO(), bson.D{{"jobName", "job01"}},
		bson.D{{"$set", bson.D{{"content", "Hello Hello"}, {"err", "err"}}}}); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result)
	fmt.Println("修改的id为:", result.UpsertedID)
}

//  修改多条
func UpdateManyDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	var (
		result *mongo.UpdateResult
		err    error
	)
	if result, err = collection.UpdateMany(context.TODO(), bson.D{{"jobName", "job02"}},
		bson.D{{"$set", bson.D{{"content", "Hello Hello"}, {"err", "err"}}}}); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result)
	// 匹配到的数量，修改的数量，新增的数量
	fmt.Println("修改结果:", result.MatchedCount, result.ModifiedCount, result.UpsertedCount)
}

// 查询一条数据
func SearchOneDataDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	data := new(LogRecord)
	err := collection.FindOne(context.TODO(), bson.D{{"jobName", "job02"}}).Decode(data)
	if err != nil {
		fmt.Println("查询错误：", err)
	} else {
		fmt.Println("查询成功：", data)
	}

}

// 匹配、时间过滤、排序、分页查询数据
func SearchMatchDemo(client *mongo.Client) {
	database := client.Database("db_test")
	collection := database.Collection("test_doc")
	var (
		result *mongo.Cursor
		err    error
	)
	logRecords := make([]*LogRecord, 0)
	var (
		skip  int64 = 1
		limit int64 = 2
	)
	result, err = collection.Find(context.TODO(), bson.D{{"jobName", "job02"},
		{"CreateTime", bson.D{{"$gt", 15}, {"$lt", 20}}}},
		&options.FindOptions{Skip: &skip, Limit: &limit, Sort: "CreateTime"})
	if err != nil {
		fmt.Println("查询错误：", err)
	} else {
		fmt.Println("总数量为：", result.RemainingBatchLength())
		for result.Next(context.Background()) {
			data := new(LogRecord)
			err = result.Decode(data)
			if err != nil {

			} else {
				logRecords = append(logRecords, data)
			}
		}
	}
	fmt.Println("查询出来的结果为：", logRecords)

}

// 查询一条数据
func SearchOneDemo(client *mongo.Client) {
	database := client.Database("db_chat_unread_new")
	collection := database.Collection("tb_chat_group_assistant_unread_new")
	data := new(UnreadChatGroupAssistantMessage)
	err := collection.FindOne(context.TODO(), bson.M{"recvuid": 3194000006, "assistantid": 20001}).Decode(data)
	if err != nil {
		fmt.Println("查询错误：", err)
	} else {
		fmt.Println("查询成功：", data)
	}

}
